package com.ganzi.ganziitem.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ganzi.ganziitem.Utils.CTool;
import com.ganzi.ganziitem.core.ControlValue;
import com.ganzi.ganziitem.netty.NettyServerListener;
import com.ganzi.ganziitem.netty.util.NettyUtil;
import com.ganzi.ganziitem.rabbit.BaseUtil;
import com.ganzi.ganziitem.rabbit.SendUtil;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CollectionServer {
    private static Logger log = LoggerFactory.getLogger(CollectionServer.class);

    @Autowired
    SendUtil senUtil;
    @Autowired
    NettyUtil nettyUtil;


    /**
     * 查询盘管状态指令
     */
    public void collection(JSONArray sendCollect){
        try {
            for(int i=0; i<sendCollect.size();i++){
                JSONObject jsonObject = (JSONObject)sendCollect.get(i);
                int allCount = jsonObject.getInteger(RabbitReceiver.ALL_COUNT);
                String ip = jsonObject.getString(RabbitReceiver.IP);
                boolean hasIp = NettyServerListener.channelMap.containsKey(ip);
                if(hasIp){
                    ChannelHandlerContext ctx = NettyServerListener.channelMap.get(ip);
                    if(ctx == null)return;
                    int number = allCount% BaseUtil.NODE>0 ? (allCount/BaseUtil.NODE)+1: allCount/BaseUtil.NODE;
                    for(int a=0;a<number;a++){
                        String firstaddr = CTool.intToHexString(BaseUtil.FIRST_ADDR + (a *BaseUtil.NODE* BaseUtil.FAN_LENGTH),2);
                        String length = CTool.intToHexString(BaseUtil.NODE * BaseUtil.FAN_LENGTH, 2);
                        String command = getQueryCommand(firstaddr,length);
                        if(command == null)continue;
                        boolean id = nettyUtil.sengcommand(ctx, command);
                        log.info("查询指令："+ctx.channel().remoteAddress()+"----:"+command+"  ---:"+id);
                        Thread.sleep(500);
                    }
                }else{
                    //返回采集器离线信息
                    senUtil.sendStateToServer(ip,1,2);
                }
            }
        }catch (Exception e){
            log.info("查询盘管状态异常："+e.getMessage());
        }
    }

    /**
     * 单个控制指令
     */
    public void controll(String type,String value,String fanNumber,String ip){
        try {
            boolean hasIp = NettyServerListener.channelMap.containsKey(ip);
            if(hasIp){
                int number = Integer.parseInt(fanNumber);
                ControlValue addrAndValue = returnControlAddrAndValue(Integer.parseInt(type), value);
                if(addrAndValue == null || number<=0)return;
                int addr = addrAndValue.getControlAddr()+BaseUtil.FIRST_ADDR;
                String controladdr = CTool.intToHexString(addr + ((number-1) * BaseUtil.FAN_LENGTH),2);
                String tempFanNumber = CTool.intToHexString(number,2);
                String tempvalue = CTool.intToHexString(addrAndValue.getControlValue(), 2);
                String tempType = CTool.intToHexString(Integer.parseInt(type),1);
                String command = getControlCommand(controladdr,tempvalue,tempFanNumber,tempType);
                if(command == null)return;
                boolean id = nettyUtil.sengcommandByIp(ip, command);
                log.info("控制指令"+command+"  ---:"+id);
            }else{
                //返回采集器离线信息
                senUtil.sendStateToServer(ip,1,2);
            }
        }catch (Exception e){
            log.info("单个控制指令异常："+e.getMessage());
        }
    }


    /**
     * 全部控制指令
     */
    public void controllAll(String type,String value,JSONArray sendCollect){
        try{
            int numType = Integer.parseInt(type);
            for(int i=0; i<sendCollect.size();i++){
                JSONObject jsonObject = (JSONObject)sendCollect.get(i);
                int allCount = jsonObject.getInteger(RabbitReceiver.ALL_COUNT);
                String ip = jsonObject.getString(RabbitReceiver.IP);
                boolean hasIp = NettyServerListener.channelMap.containsKey(ip);
                if(hasIp){
                    ChannelHandlerContext ctx = NettyServerListener.channelMap.get(ip);
                    ControlValue addrAndValue = returnControlAddrAndValue(Integer.parseInt(type), value);
                    if(addrAndValue == null)continue;
                    for(int a=0;a<allCount;a++){
                        int addr = addrAndValue.getControlAddr()+BaseUtil.FIRST_ADDR;
                        String controladdr = CTool.intToHexString(addr + (a * BaseUtil.FAN_LENGTH),2);
                        String fanNumber = CTool.intToHexString(a+1,2);
                        String tempvalue = CTool.intToHexString(addrAndValue.getControlValue(), 2);
                        String tempType = CTool.intToHexString(numType,1);
                        String command = getControlCommand(controladdr,tempvalue,fanNumber,tempType);
                        if(command == null)continue;
                        boolean id = nettyUtil.sengcommand(ctx, command);
                        log.info("控制指令："+ctx.channel().remoteAddress()+"----:"+command+"  ---:"+id);
                        Thread.sleep(500);
                    }
                }else{
                    //返回采集器离线信息
                    senUtil.sendStateToServer(ip,1,2);
                }
            }
        }catch (Exception e){
            log.info("控制全部指令异常："+e.getMessage());
        }
    }

    /**
     * 发送学校和采集器在线状态(同时发送采集器在线信息，是为了服务器根据采集器在线状态启动查询线程)
     */
    public void sendState(){
        senUtil.sendCollectionStateToServer();
    }

    /**
     * 发送采集器在线状态
     */
    public void sendCollectionState(){
        senUtil.sendCollectionStateToServer();
    }


    /**
     * 解析服务器指令
     * */
    public ControlValue returnControlAddrAndValue(int type, String value){
        switch (type){
            case BaseUtil.TURN:
                switch (value){
                    case "1":
                        return ControlValue.builder().controlAddr(1).controlValue(1).build();//开机
                    case "0":
                        return ControlValue.builder().controlAddr(1).controlValue(2).build();//关机
                    default:
                        return null;
                }
            case BaseUtil.MODEL:
                switch (value){
                    case "1":
                        return ControlValue.builder().controlAddr(2).controlValue(1).build();//制冷
                    case "2":
                        return ControlValue.builder().controlAddr(2).controlValue(2).build();//制热
                    case "3":
                        return ControlValue.builder().controlAddr(2).controlValue(3).build();//除湿
                    default:
                        return null;
                }
            case BaseUtil.WIND:
                switch (value){
                    case "1":
                        return ControlValue.builder().controlAddr(3).controlValue(1).build();//高
                    case "2":
                        return ControlValue.builder().controlAddr(3).controlValue(2).build();//中
                    case "3":
                        return ControlValue.builder().controlAddr(3).controlValue(3).build();//低
                    case "4":
                        return ControlValue.builder().controlAddr(3).controlValue(4).build();//自动
                    default:
                        return null;
                }
            case BaseUtil.TEMP:
                return ControlValue.builder().controlAddr(4).controlValue(Integer.parseInt(value)).build();//温度
            case BaseUtil.LOOP:
                switch (value){
                    case "1":
                        return ControlValue.builder().controlAddr(5).controlValue(1).build();//内循环
                    case "2":
                        return ControlValue.builder().controlAddr(5).controlValue(2).build();//全新风
                    case "3":
                        return ControlValue.builder().controlAddr(5).controlValue(3).build();//自动
                    default:
                        return null;
                }
            default:
                return null;
        }
    }

    /**
     * 组装查询指令
     * */
    public String getQueryCommand(String firstaddr,String length){
        if(StringUtils.isNotBlank(firstaddr) && StringUtils.isNotBlank(length)){
            return "EE03"+firstaddr+"0008"+"0103"+firstaddr+length;
        }else{
            return null;
        }
    }

    /**
     * 组装控制指令
     * */
    public String getControlCommand(String controladdr,String value,String fanNumber,String type){
        if(StringUtils.isNotBlank(controladdr) && StringUtils.isNotBlank(value)){
            return "EE"+type+fanNumber+"0008"+"0106"+controladdr+value;
        }else{
            return null;
        }
    }
}
